package whisper.service.repository.impl;

import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import whisper.service.domain.db.SourceMedia;
import whisper.service.repository.SourceMediaRepository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by JT on 2017/11/18.
 */
@Repository
public class SourceMediaRepositoryImpl implements SourceMediaRepository {

    private static final String TABLE_NAME_SOURCE_MEDIA = "WM_SOURCE";

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public long saveSourceMedia(SourceMedia sourceMedia) {
        String sql = String.format("INSERT INTO %s(ORIGINALNAME, SOURCENAME, SOURCEPATH, SOURCESIZE, SOURCETYPE) VALUES (?, ?, ?, ?, ?)",
                TABLE_NAME_SOURCE_MEDIA);

        KeyHolder keyHolder = new GeneratedKeyHolder();

        jdbcTemplate.update(new PreparedStatementCreator() {
            PreparedStatement ps = null;
            @Override
            public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
                ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                ps.setString(1, Optional.fromNullable(sourceMedia.getOriginalName()).or(""));
                ps.setString(2, Optional.fromNullable(sourceMedia.getSourceName()).or(""));
                ps.setString(3, Optional.fromNullable(sourceMedia.getSourcePath()).or(""));
                ps.setString(4, Optional.fromNullable(sourceMedia.getSourceSize()).or(""));
                ps.setString(5, Optional.fromNullable(sourceMedia.getSourceType()).or(""));
                return ps;
            }
        }, keyHolder);
        return keyHolder.getKey().longValue();
    }
}
